package com.fastjrun.security.authentication.mobile;

import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用于校验用户手机号是否允许通过认证
 */
public class MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter {


    public MobileAuthenticationFilter() {
        super(new AntPathRequestMatcher("/mobile/login", HttpMethod.POST.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        // 先获取seesion中的手机号
        String phone =
                (String) request.getSession().getAttribute(MobileConstants.SESSION_KEY_MOBILE);
        request.getSession().removeAttribute(MobileConstants.SESSION_KEY_MOBILE);
        MobileAuthenticationToken authRequest = new MobileAuthenticationToken(phone);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * 将 sessionID和hostname添加 到MobileAuthenticationToken
     */
    protected void setDetails(HttpServletRequest request,
                              MobileAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
